package cn.xenosp.server.common.tools;

import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.system.oshi.OshiUtil;
import lombok.extern.slf4j.Slf4j;
import oshi.PlatformEnum;
import oshi.SystemInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

/**
 * 项目名： service-web
 * 包路径： cn.xenosp.nginx.common
 * 作者：   TongHui
 * 创建时间: 2024-07-29 14:17
 * 描述: TODO
 * 版本: 1.0
 */
@Slf4j
public class ServiceUtil extends OshiUtil {

    private static final long SLEEP_TIME = 1000;
    public static boolean isWINDOWS() {
        return SystemInfo.getCurrentPlatform() == PlatformEnum.WINDOWS;
    }

    public static boolean isLINUX() {
        return SystemInfo.getCurrentPlatform() == PlatformEnum.LINUX;
    }

    public static boolean isNginxRun(){
        if (isWINDOWS()){
            String rs = RuntimeUtil.execForStr("tasklist /FI \"IMAGENAME eq nginx.exe\"");
            return rs.toLowerCase().contains("nginx.exe");
        }else if (isLINUX()){
            String[] command = { "/bin/sh", "-c", "pgrep -c nginx" };
            String rs = RuntimeUtil.execForStr(command);
            return !rs.equals("0");
        }
        return false;
    }

    public static boolean isRedisRun(){
        if (isWINDOWS()){
            String rs = RuntimeUtil.execForStr("tasklist /FI \"IMAGENAME eq redis-server.exe\"");
            return rs.toLowerCase().contains("redis-server");
        }else if (isLINUX()){
            String[] command = { "/bin/sh", "-c", "pgrep -c redis" };
            String rs = RuntimeUtil.execForStr(command);
            return !rs.equals("0");
        }
        return false;
    }

    private static final Pattern mobilePattern = Pattern.compile("(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino", Pattern.CASE_INSENSITIVE);

    public static boolean isMobileDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent!= null) {
            return mobilePattern.matcher(userAgent).find();
        }
        return false;
    }
}
